<template>
	<view class="container">
		<!-- 头部页签 -->
		<view class="header" ref="formRef">
			<my-tab :tabData="tabData" :tabCurrent="tabCurrent" @handleClick="handleTabClick"></my-tab>
		</view>
		<!-- 颈部查询 -->
		<view class="navbar">
			<view class="search-fixed">
				<template v-for="(key,keyIndex) in Object.keys(formList)">
					<template v-if="key==tabCurrent">
						<view class="search-item" v-for="(item,index) in formList[key]" :key="index">
							<view class="label">
								{{ item.label}}
							</view>
							<u-input v-if="item.type==='commonbox'" v-model="form[key][item.prop]"
								:placeholder="item.placeholder||'请选择'" border type="select"
								@click="openSelect(item.type)"></u-input>
							<u-input v-else-if="item.type==='datepicker'" v-model="form[key][item.prop]"
								:placeholder="item.placeholder||'请选择'" border type="select"
								@click="openSelect(item.type)"></u-input>
							<u-input v-else-if="item.type==='weekpicker'" v-model="form[key][item.prop+'label']"
								:placeholder="item.placeholder||'请选择'" border type="select"
								@click="openSelect(item.type)"></u-input>
							<u-input v-else v-model="form[key][item.prop]" :placeholder="item.placeholder||'请输入'"
								border></u-input>
						</view>
					</template>

				</template>

				<view class="button-part">
					<u-button type="primary" size="mini" @click="dataSearch">查询</u-button>
				</view>
			</view>

		</view>
		<!-- 数据表格 -->
		<view class="content">
			<template v-if="Object.keys(tableDatas.groupByDatas).length">
				<view class="content-item" v-for="(item,index) in Object.keys(tableDatas.groupByDatas)">
					<view class="title">
						PO号：{{ item }}
					</view>
					<view class="table">
						<u-table font-size="20">
							<u-tr>
								<u-th v-for="(col,colIndex) in tableDatas.columns" :key="colIndex+'-'+tabCurrent"
									:width="col.width">
									{{col.label}}
								</u-th>
							</u-tr>
							<u-tr v-for="(row,rowIndex) in tableDatas.groupByDatas[item]"
								:key="rowIndex+'-'+tabCurrent">
								<u-td v-for="(col,colIndex) in tableDatas.columns" :key="colIndex" :width="col.width"
									:class="`col-${colIndex} ${col.prop==='edit'?'col-edit':''}`"
									@click.native="clickRow(row,col)">
									{{ row[col.prop]}}
								</u-td>
							</u-tr>
						</u-table>
					</view>
				</view>
			</template>
			<u-empty v-else text="暂无数据" mode="list"></u-empty>
		</view>
		<!-- 日期选择 -->
		<u-calendar v-model="selectConfig.datepicker" @change="selectChange($event,'datepicker')"
			max-date="2125-01-01"></u-calendar>
		<!--人员选择 -->
		<u-select v-model="selectConfig.commonbox" :list="selectConfig.commonboxItems"
			@confirm="selectChange($event,'commonbox')"></u-select>
		<!-- 选择周次 -->
		<u-picker mode="selector" :range="weekOptions" v-model="selectConfig.weekpicker"
			@confirm="selectChange($event,'weekpicker')" :default-selector="[form[1]['WK']-1||0]"></u-picker>
	</view>
</template>

<script>
	import myTab from '@/components/myTabs/index.vue'
	export default {
		components: {
			myTab
		},
		data() {
			const today = this.$u.timeFormat(new Date, 'yyyy-mm-dd')
			return {
				tabData: ['每日进度', '每周进度'],
				tabCurrent: 0,
				formList: {
					0: [{
							label: '日期：',
							prop: 'CreatedOn',
							placeholder: '前选择日期',
							type: 'datepicker',
							value: today
						},
						{
							label: '人员：',
							prop: 'Names',
							placeholder: '请选择人员',
							type: 'commonbox'
						},
					],
					1: [{
							label: '周次：',
							prop: 'WK',
							placeholder: '请选择周次',
							type: 'weekpicker',
							value: this.getWeekNumber()
						},
						{
							label: '人员：',
							prop: 'Names',
							placeholder: '请选择人员',
							type: 'commonbox',
						},
					]
				},
				form: {
					0: {

					},
					1: {

					}
				},
				tableDatas: {
					dicID: 7848,
					datas: [],
					groupByDatas: {},
					columns: [],
					allcolumns: [
						[{
								prop: 'MaterialName',
								label: '组件',
								width: '20%'
							},
							{
								prop: 'PreparePlanName',
								label: '任务',
								width: '41%'
							},
							{
								prop: 'Names',
								label: '人员',
								width: '15%'
							},
							{
								prop: 'AddTaskProgress',
								label: '今日',
								width: '12%'
							},
							{
								prop: 'TaskProgress',
								label: '总进度',
								width: '12%'
							},

						],
						[{
								prop: 'MaterialName',
								label: '组件',
								width: '20%'
							},
							{
								prop: 'PreparePlanName',
								label: '任务',
								width: '30%'
							},
							{
								prop: 'Names',
								label: '人员',
								width: '15%'
							},
							{
								prop: 'WKAddTaskProgress',
								label: '周进度',
								width: '17%'
							},
							{
								prop: 'WKTaskProgress',
								label: '总进度',
								width: '18%'
							},

						],

					],
					formData: {},
					loading: false,
					loadmoreVisible: 'loadmore',
					loadText: '滚动或点击加载更多',
					count: 0,
					selectAll: false
				},
				selectConfig: {
					commonbox: false,
					datepicker: false,
					weekpicker: false,
					commonboxItems: []
				},
				weekOptions: [],
			}
		},
		onLoad() {
			// 周选择配置
			// 1. 获取当前年份总周数
			const totalWeeks = this.getTotalWeeks();
			// 2. 生成周次选项数组
			this.weekOptions = Array.from({
				length: totalWeeks
			}, (_, i) => 'week' + (i + 1));
			// 初始化表格数据
			this.formList[0].forEach(val => {
				this.$set(this.form[0], val.prop, val.value || null)
			})
			this.formList[1].forEach(val => {
				this.$set(this.form[1], val.prop, val.value || null)
				if (val.prop === 'WK') {
					this.$set(this.form[1], val.prop + 'label', val.value ? 'week' + val.value : '' || null)
				}
			})
			this.$set(this.tableDatas, 'columns', this.tableDatas.allcolumns[0])
			this.getWarehouseAccount()
			this.getApsData()
		},
		methods: {
			// 获取车间人员数据源
			async getWarehouseAccount() {
				const condition = {
					DataSourceID: 'D202504180001'
				}
				const res = await this.$request.post({
					url: '/APSAPI/GetDataSource',
					data: condition
				}).catch(err => err)
				if (res.result) {
					const item = res.data.map(val => ({
						value: val.Name,
						label: val.Name
					}))
					item.unshift({
						value: '',
						label: '全部'
					})
					this.$set(this.selectConfig, 'commonboxItems', item)
				}
			},
			//页签切换
			handleTabClick(index) {
				if (index === this.tabCurrent) return
				if (index === 0) {
					this.tableDatas.dicID = 7848
				} else {
					this.tableDatas.dicID = 7845
				}
				// this.form.page = 1
				this.tabCurrent = index
				this.$set(this.tableDatas, 'columns', this.tableDatas.allcolumns[index])
				this.getApsData()
			},
			dataSearch() {
				this.getApsData()
			},
			// 获取数据
			async getApsData(remark = 0) {
				const condition = {
					dicID: this.tableDatas.dicID,
				}
				Object.assign(condition, this.form[this.tabCurrent])
				this.tableDatas.loading = true
				const res = await this.$request.post({
					url: '/APSAPI/APSData',
					data: condition
				}).catch(err => err)
				this.tableDatas.loading = false
				if (!res) return
				const {
					result,
					msg,
					data,
					count
				} = res
				if (!result) return uni.showToast({
					title: msg,
					icon: 'error'
				})
				if (res.result) {
					this.$set(this.tableDatas, 'count', count)
					const groupByDatas = this.groupBySourceOrderNo(res.data)
					this.$set(this.tableDatas, 'datas', res.data)
					this.$set(this.tableDatas, 'groupByDatas', groupByDatas)
				} else {
					return Promise.reject()
				}
			},
			clickRow(row, col) {
				if (col.prop !== 'edit') return
				this.$u.route({
					url: '/pages/Isgo/outbound/orderOutbounSetting',
					params: {
						row: JSON.stringify(row) // 转成字符串传递
					}
				});
			},
			// 数据分组
			groupBySourceOrderNo(data) {
				return data.reduce((acc, item) => {
					const key = item.SourceOrderNo;
					if (!acc[key]) {
						acc[key] = [];
					}
					acc[key].push(item);
					return acc;
				}, {});
			},
			// 打开选择起
			openSelect(type) {
				this.$set(this.selectConfig, type, true)
			},
			// 选择器变化
			selectChange(e, type) {
				if (type === 'commonbox') {
					this.$set(this.form[this.tabCurrent], 'Names', e[0].value)
				} else if (type === 'datepicker') {
					this.$set(this.form[this.tabCurrent], 'CreatedOn', e.result)
				} else if (type === 'weekpicker') {
					this.$set(this.form[this.tabCurrent], 'WK', e[0] + 1)
					this.$set(this.form[this.tabCurrent], 'WKlabel', 'week' + (e[0] + 1))
				}
				this.dataSearch()
			},
			// 获取当前周
			getWeekNumber(date = new Date()) {
				const now = new Date(date);
				const startOfYear = new Date(now.getFullYear(), 0, 1);

				// 处理1月1日是周日的情况
				if (startOfYear.getDay() === 0 && now.getTime() === startOfYear.getTime()) {
					return 1;
				}

				const days = Math.floor((now - startOfYear) / (24 * 60 * 60 * 1000));
				let week = Math.ceil((days + startOfYear.getDay() + 1) / 7);

				// 特殊处理周日
				if (now.getDay() === 0) week--;

				// 确保周数不小于1
				return Math.max(1, week);
			},
			// 获取当前年份总周数
			getTotalWeeks() {
				const year = new Date().getFullYear();
				const dec31 = new Date(year, 11, 31);

				// 计算12月31日是第几周
				let totalWeeks = this.getWeekNumber(dec31);

				// 如果12月31日是周日，需要特殊处理
				if (dec31.getDay() === 0) {
					totalWeeks = this.getWeekNumber(new Date(year, 11, 30));
				}
				return totalWeeks;
			},
		}
	}
</script>

<style scoped lang="scss">
	* {
		box-sizing: border-box;
	}

	.container {
		width: 100%;
		// height: 100vh;
		// overflow: hidden;

		.header {
			height: 80rpx;
			// border-bottom: 1px solid $uni-border-color;
		}

		.navbar {
			padding: 0 10rpx;
			height: 80rpx;

			.search-fixed {
				position: fixed;
				left: 0;
				display: flex;
				flex-wrap: nowrap;
				background-color: $uni-bg-color;
			}

			.search-item {
				flex-grow: 1;
				padding-right: 20rpx;
				display: flex;
				flex-wrap: nowrap;
				align-items: center;

				.uni-input-input {
					font-size: small !important;
				}

				.uni-input-placeholder {
					font-size: small !important;
				}

				::v-deep .u-input__input {
					font-size: small !important;
				}
			}

			.button-part {
				width: 150rpx;
				display: flex;
				align-items: center;
				justify-content: center;
			}
		}

		.content {
			width: 100%;
			// flex: 1;
			display: flex;
			flex-direction: column;
			padding: 10rpx 10rpx 20rpx;
			overflow: hidden;
			gap: 10rpx;

			.content-item {
				margin-bottom: 10rpx;
				.title {
					font-size: large;
					font-weight: bold;
					padding: 10rpx;
					background: linear-gradient(to right, rgb(184, 230, 236), #fff) !important;
				}
			}

			.u-td,
			.u-th {
				white-space: nowrap !important;
				overflow: hidden !important;
				text-overflow: ellipsis !important;
				min-width: 0 !important;
				/* 关键属性 */
				flex-shrink: 0 !important;
				/* 防止flex容器压缩 */
			}

			.u-td {
				height: 80rpx;
			}

			.col-1 {
				white-space: pre-wrap !important;
				font-weight: bold;
				// font-size: 18rpx !important;
				text-align: left !important;
			}

			.col-0 {
				// font-size: 20rpx !important;
				white-space: pre-wrap !important;
				font-weight: bold;
				
			}

			.col-3 {
				background-color: rgb(251, 255, 202) !important;
				color:red !important;
			}

			.col-edit {
				color: $uni-color-primary !important;
				text-decoration-line: underline;
			}
			.col-3,.col-4{
				font-size: 24rpx !important;
				font-weight: bold;
			}

		}

		.footer {
			height: 60rpx;
			display: flex;
			justify-content: center;
			align-items: center;
			padding-right: 20rpx;
		}
	}
</style>